package com.chookss.home.audit.project;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.audit.ApprovalProcessActivity;
import com.chookss.home.audit.clockIn.ClockInUtils;
import com.chookss.home.entity.ProcessEntity;
import com.chookss.home.entity.ReimbursementDetailEntity;
import com.chookss.tools.ClearMoreZeroUtil;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.CircleImageView;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GroupDetailActivity extends BaseAct {
    //项目金额、回款金额详情页
    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.common_right_txt)
    TextView common_right_txt;
    @BindView(R.id.tvCurrentMoneyInit)
    TextView tvCurrentMoneyInit;
    @BindView(R.id.tvCurrentMoney)
    TextView tvCurrentMoney;
    @BindView(R.id.tvMoneyInit)
    TextView tvMoneyInit;
    @BindView(R.id.tvMoney)
    TextView tvMoney;
    @BindView(R.id.emptyPost)
     View emptyPost;
    @BindView(R.id.llPost)
    LinearLayout llPost;
    @BindView(R.id.tvPost)
    TextView tvPost;
    @BindView(R.id.emptyGroup)
    View emptyGroup;
    @BindView(R.id.tvGroup)
    TextView tvGroup;
    @BindView(R.id.llGroup)
    LinearLayout llGroup;
    @BindView(R.id.edContent)
    TextView edContent;
    @BindView(R.id.tvSure)
    TextView tvSure;
    @BindView(R.id.tvCancel)
    TextView tvCancel;
    @BindView(R.id.llBottom)
    LinearLayout llBottom;
    @BindView(R.id.llProcess)
    LinearLayout llProcess;
    @BindView(R.id.llProcessTop)
    LinearLayout llProcessTop;
    @BindView(R.id.ivHead)
    CircleImageView ivHead;
    @BindView(R.id.tvProcessTitle)
    TextView tvProcessTitle;
    @BindView(R.id.tvProcessTitleInit)
    TextView tvProcessTitleInit;
    @BindView(R.id.tvProcessStatus)
    TextView tvProcessStatus;
    @BindView(R.id.emptyProcess)
    View emptyProcess;
    @BindView(R.id.emptyBottom)
    View emptyBottom;
    @BindView(R.id.llAudit)
    LinearLayout llAudit;
    @BindView(R.id.edAudit)
    EditText edAudit;
    private String workflowId = "", id = "", repairCode = "";
    private String  employeeCode;
    private ReimbursementDetailEntity reimbursementDetailEntity;
    private int type=17;//17项目金额 16回款金额

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_detail);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        repairCode = getIntent().getStringExtra("repairCode");
        type=getIntent().getIntExtra("type",17);
        common_right_txt.setText("审批流程");
        common_right_txt.setVisibility(View.VISIBLE);
        if (type == 17) {
            commonTitleTxt.setText("项目金额详情");
            tvCurrentMoneyInit.setText("当前项目金额");
            tvMoneyInit.setText("变更项目金额");
        } else {
            commonTitleTxt.setText("回款金额详情");
            tvCurrentMoneyInit.setText("当前回款总金额");
            tvMoneyInit.setText("本次回款金额");
        }
        selectGoodsInfDetail();
    }

    private void selectGoodsInfDetail() {
        //审批基本数据
        Map<String, String> map = new HashMap<>();
        map.put("projectCode", repairCode);
        map.put("type", type+"");   // 1-新闻 2-视频 3-补卡 4-请假 5-外勤 6-图文7报销8物料9借款
        showLoading();
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<ReimbursementDetailEntity>>() {
        }.getType(), null, Urls.selectKaoqinDeail, SignUtils2.makeSignStr(map), false, new ObserverCallback<ReimbursementDetailEntity>() {
            @Override
            public void onSuccess(ReimbursementDetailEntity data) {
                dismissLoading();
                if (data != null) {
                    if (tvMoney == null) {
                        return;
                    }
                    reimbursementDetailEntity = data;
                    workflowId = data.getWorkflowId();
                    id = data.getId();
                    repairCode = data.getProjectCode();
                    employeeCode = data.getCreateEmployeeCode();
                    if (Utils.isNull(data.getRemark())) {
                        edContent.setText("无");
                    } else {
                        edContent.setText(data.getRemark());
                    }
                    tvCurrentMoney.setText(ClearMoreZeroUtil.subZeroAndDot(data.getOldAmt()) + "元");
                    tvMoney.setText( ClearMoreZeroUtil.subZeroAndDot(data.getAmt()) + "元");
                    if (!Utils.isNull(data.getGroupCode())) {
                        tvGroup.setText(data.getGroupName() + "(" + ClockInUtils.getGroupEnd(data.getGroupCode()) + ")");
                        llGroup.setVisibility(View.VISIBLE);
                        emptyGroup.setVisibility(View.VISIBLE);
                    }
                    if (!Utils.isNull(data.getOrgName())) {
                        tvPost.setText(data.getOrgName());
                        llPost.setVisibility(View.VISIBLE);
                        emptyPost.setVisibility(View.VISIBLE);
                    }
                    //0么有权限1展示通过不通过2展示废弃修改
                    if (Utils.isNull(data.getAuditFlag())) {
                        llBottom.setVisibility(View.GONE);
                        getProcessData();
                    } else {
                        if ("1".equals(data.getAuditFlag()) || "2".equals(data.getAuditFlag())) {
                            llBottom.setVisibility(View.VISIBLE);
                            if ("2".endsWith(data.getAuditFlag())) {
                                tvSure.setText("修改");
                                tvCancel.setText("废弃");
                            }else{
                                llAudit.setVisibility(View.VISIBLE);
                            }
                        } else {
                            llBottom.setVisibility(View.GONE);
                            getProcessData();
                        }

                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    private void getProcessData() {
        //审批进度
        Map<String, String> map = new HashMap<>();
        map.put("projectCode", repairCode);
        map.put("type", type + "");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<ProcessEntity>>>() {
        }.getType(), null, Urls.selectAuditDetailList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<ProcessEntity>>() {
            @Override
            public void onSuccess(List<ProcessEntity> data) {
                String name = "", headUrl = "";
                List<ProcessEntity> processEntityList = new ArrayList<>();
                for (int i = 0; i < data.size(); i++) {
                    processEntityList.add(data.get(i));
                    if (data.get(i).getConnectType().equals("0")) {
                        name = data.get(i).getCreateEmployeeName();
                        headUrl = data.get(i).getHeadPhotoThumbUrl();
                    }
                    if (data.get(i).getEndStep().equals("1")) {
                        ProcessEntity endProcessEntity = new ProcessEntity();
                        if (Utils.isNull(name)) {
                            endProcessEntity.setCreateEmployeeName(data.get(0).getCreateEmployeeName());
                            endProcessEntity.setRealAuditEmployeeName(data.get(0).getCreateEmployeeName());
                        } else {
                            endProcessEntity.setCreateEmployeeName(name);
                            endProcessEntity.setRealAuditEmployeeName(name);
                        }
                        if (Utils.isNull(headUrl)) {
                            endProcessEntity.setHeadPhotoThumbUrl(data.get(0).getHeadPhotoThumbUrl());
                        } else {
                            endProcessEntity.setHeadPhotoThumbUrl(headUrl);
                        }
                        endProcessEntity.setConnectType("0");
                        endProcessEntity.setEndProcess(true);
                        endProcessEntity.setAuditStatus("1");
                        processEntityList.add(endProcessEntity);
                    }
                }
                if (data.size() > 0) {
                    llProcess.setVisibility(View.VISIBLE);
                    emptyProcess.setVisibility(View.VISIBLE);
                    emptyBottom.setVisibility(View.GONE);
                    setProcessDetail(processEntityList.get(processEntityList.size() - 1));
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void setProcessDetail(ProcessEntity entity) {
        if (!Utils.isNull(entity.getHeadPhotoThumbUrl())) {
            GlideUtils.loadAvatar(this, entity.getHeadPhotoThumbUrl(), ivHead);
        } else {
            GlideUtils.loadAvatar(this, new ShareUtils().getString(this, StaticClass.ORIGINALURL, ""), ivHead);
        }
        if (entity.isEndProcess()) {
            //已结束
            llProcessTop.setVisibility(View.GONE);
            tvProcessStatus.setText("已结束");
            tvProcessStatus.setTextColor(Color.parseColor("#00C993"));
        } else {
            //getWorkFlowName  环节名称
            //getAuditEmployeeName  项目组
            //getRealAuditEmployeeName   真实审批人
            // connectType //0发起人1行政审批  只有0和1不展示（）中的项目名称，其余的需要展示
            //格式 环节名称（项目名称）
            if ("0".equals(entity.getConnectType()) || "1".equals(entity.getConnectType())) {
                tvProcessTitle.setText(entity.getWorkFlowName());
            } else {
                if (Utils.isNull(entity.getWorkFlowName())) {
                    tvProcessTitle.setText(entity.getWorkFlowName());
                    tvProcessTitleInit.setText(entity.getAuditEmployeeName());
                } else {
                    if (Utils.isNull(entity.getAuditEmployeeName())) {
                        tvProcessTitle.setText(entity.getWorkFlowName());
                        tvProcessTitleInit.setText("");
                    } else {
                        tvProcessTitle.setText(entity.getWorkFlowName());
                        tvProcessTitleInit.setText("(" + entity.getAuditEmployeeName() + ")");
                    }
                }
            }
            //1审核通过 2审核未通过0未审核3废弃
            if ("0".equals(entity.getAuditStatus())) {
                if ("0".equals(entity.getConnectType())) {
                    tvProcessStatus.setText("待修改");
                } else {
                    if (Utils.isNull(entity.getAuditEmployeeName())) {
                        tvProcessStatus.setText("待审批");
                    } else {
                        tvProcessTitleInit.setText("");
                        tvProcessStatus.setText("待" + entity.getAuditEmployeeName() + "审批");
                    }

                }
                tvProcessStatus.setTextColor(Color.parseColor("#FCA817"));
            } else if ("1".equals(entity.getAuditStatus())) {
                if ("0".equals(entity.getConnectType())) {
                    tvProcessStatus.setText("重新提交");
                } else {
                    if ("1".equals(entity.getReplaceCd())) {
                        //超管待审
                        tvProcessStatus.setText("超管代审批通过");
                    } else {
                        tvProcessStatus.setText("审批通过");
                    }

                }
                tvProcessStatus.setTextColor(Color.parseColor("#00C993"));
            } else {
                if ("3".equals(entity.getAuditStatus())) {
                    tvProcessStatus.setText("废弃");
                } else {
                    if ("1".equals(entity.getReplaceCd())) {
                        //超管待审
                        tvProcessStatus.setText("超管代审批不通过");
                    } else {
                        tvProcessStatus.setText("审批不通过");
                    }
                }
                tvProcessStatus.setTextColor(getResources().getColor(R.color.main_color));
            }
        }
    }

    private void passData(int auditStatus) {
        Map<String, Object> map = new HashMap<>();
        //1审核通过 2审核未通过0未审核
        Map<String, String> news = new HashMap<>();
        List<Map<String, String>> lists = new ArrayList<>();
        news.put("id", workflowId);
        news.put("projectCode", repairCode);
//        ////0新闻2图文3补卡4请假
        news.put("type", type+"");
        news.put("auditStatus", auditStatus + "");
        news.put("employeeCode", employeeCode);
        if(!Utils.isNull(edAudit.getText().toString())){
            news.put("remark", edAudit.getText().toString());
        }
        lists.add(news);
        map.put("tbKmerWorkFlowProjects", XJson.listToJsArrays(lists));
        showLoading();
        MyHttpRequest.postRequestJson(Urls.auditWorkfolwProject, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("提交成功");
                        EventBus.getDefault().post(new MyEvent("RefreshGroupRecord"));
                        finish();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("提交失败，请稍后重试");
                }
            }
        });
    }

    private void deleteData() {
        Map<String, String> map = new HashMap<>();
        map.put("workflowId", workflowId);
        map.put("qingjiaWorkflowCode", repairCode);
        map.put("workflowType", type+"");
        showLoading();
        MyHttpRequest.postRequest(Urls.deleteQingjiaInfo, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("提交成功");
                        EventBus.getDefault().post(new MyEvent("RefreshGroupRecord"));
                        finish();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("提交失败，请稍后重试");
                }
            }
        });
    }
    @OnClick({R.id.common_title_back, R.id.llProcess, R.id.common_right_txt, R.id.tvCancel, R.id.tvSure})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.common_right_txt:
            case R.id.llProcess:
                if (Urls.antiShake.check()) {
                    return;
                }
                intent = new Intent(this, ApprovalProcessActivity.class);
                intent.putExtra("projectCode", repairCode);
                intent.putExtra("type", type);
                startActivity(intent);
                break;
            case R.id.tvCancel:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (tvCancel.getText().toString().equals("不通过")) {
                    passData(2);
                } else {
                    deleteData();
                }
                break;
            case R.id.tvSure:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (tvSure.getText().toString().equals("通过")) {
                    passData(1);
                }  else {
                    intent = new Intent(this, GroupMoneyActivity.class);
                    intent.putExtra("repairCode", repairCode);
                    intent.putExtra("workflowId", workflowId);
                    if(type==17){
                        intent.putExtra("type", 0);
                    }else{
                        intent.putExtra("type", 1);
                    }
                    startActivity(intent);
                    finish();
                }
                break;
        }
    }


}
